package Dao.DaoImpl;

import Dao.DormDao;
import Utils.JDBCUtils;
import domain.Dorm;
import domain.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class DormDaoImpl implements DormDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public void addDorm(Dorm dorm) {
        String sql ="insert into dorm values(?,?,?,?,?,?,?,null,null,?,null)";
        template.update(sql,dorm.getDormnum(),dorm.getMember1(),dorm.getMember2(),dorm.getMember3(),dorm.getMember4(),dorm.getMember5(),dorm.getMember6(),dorm.getHead());
    }

    @Override
    public List<Dorm> fuzzySelectDorm(HashMap<String, String> map) {
        String sql = "select * from dorm where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        Set<String> set = map.keySet();
        List<Object> params = new ArrayList<Object>();
        for (String key : set) {
            String value = map.get(key);

            //判断value是否有值
            if(value!=null && !"".equals(value)){
                //有值就拼接
                sb.append(" and "+key+" like ?");
                params.add("%"+value+"%");//上面 ? 的值
            }
        }
        sql = sb.toString();
        return template.query(sql,new BeanPropertyRowMapper<Dorm>(Dorm.class),params.toArray());
    }

    @Override
    public List<Dorm> dormList() {
        String sql = "select * from dorm";
        return template.query(sql,new BeanPropertyRowMapper<Dorm>(Dorm.class));
    }

    @Override
    public Dorm selectDormByDormnum(String dormnum) {
        String sql ="select * from dorm where dormnum = ?";
        return template.queryForObject(sql,new BeanPropertyRowMapper<Dorm>(Dorm.class),dormnum);
    }

    @Override
    public void updateDorm(Dorm dorm) {
        String sql = "update dorm set member1=?,member2=?,member3=?,member4=?,member5=?,member6=?,water=?,ele=?,head=?,level=? where dormnum=?";
        template.update(sql,dorm.getMember1(),dorm.getMember2(),dorm.getMember3(),dorm.getMember4(),dorm.getMember5(),dorm.getMember6(),dorm.getWater(),dorm.getEle(),dorm.getHead(),dorm.getLevel(),dorm.getDormnum());
    }

    @Override
    public void deleteDorm(String dormnum) {
        String sql ="delete from dorm where dormnum = ?";
        template.update(sql,dormnum);
    }

    @Override
    public void payWater(Double money, String dormnum) {
        String sql ="update dorm set water=? where dormnum=?";
        template.update(sql,money,dormnum);
    }

    @Override
    public void payEle(Double money, String dormnum) {
        String sql ="update dorm set ele=? where dormnum=?";
        template.update(sql,money,dormnum);
    }




}
